package vip.zhenzicheng.websocket.websocket.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
import vip.zhenzicheng.websocket.websocket.config.interceptor.TokenInterceptor;
import vip.zhenzicheng.websocket.websocket.handler.WebSocketConnection;
import vip.zhenzicheng.websocket.websocket.handler.WebSocketServer;

/**
 * <a href="http://centphp.com/websocket">WebSocket在线测试工具</a>
 */
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    /**
     * 监听使用 @ServerEndpoint 暴露的服务
     *
     * @see WebSocketServer
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

    /**
     * 监听 WebSocket Handler，需要添加 @EnableWebSocket 开启监听功能
     */
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        // handler方式手动注入
        registry.addHandler(handler(), "/ws/handler")
                .setAllowedOrigins("*")
                .addInterceptors(tokenInterceptor());
    }

    @Bean
    public WebSocketConnection handler() {
        return new WebSocketConnection();
    }

    /**
     * 有必要可以添加拦截器
     */
    @Bean
    public TokenInterceptor tokenInterceptor() {
        // return new TokenInterceptor();
        return null;
    }

}
